const { app, BrowserWindow, ipcMain, dialog } = require('electron')
const path = require('path')
const fs = require('fs')

let mainWindow

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 700,
    minWidth: 100,
    minHeight: 100,
    transparent: true, // 透明背景
    frame: false, // 无边框窗口
    titleBarStyle: 'hiddenInset', // 隐藏标题栏
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    },
    show: false
  })

  // 开发环境加载 Vite 服务器
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:5173')
    mainWindow.webContents.openDevTools()
  } else {
    // 生产环境加载构建后的文件
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 处理窗口透明度设置
ipcMain.on('set-window-transparent', (event, transparent) => {
  if (mainWindow) {
    mainWindow.setOpacity(transparent ? 0.95 : 1.0)
  }
})

// 处理窗口尺寸调整
ipcMain.on('resize-window', (event, width, height) => {
  if (mainWindow) {
    mainWindow.setSize(parseInt(width), parseInt(height))
  }
})

// 处理窗口拖拽
ipcMain.on('start-drag', (event) => {
  if (mainWindow) {
    mainWindow.startDrag()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

// 检测文件编码
function detectEncoding(buffer) {
  // 检测 UTF-8 BOM
  if (buffer.length >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
    return 'utf8'
  }
  
  // 检测 UTF-16 BOM
  if (buffer.length >= 2) {
    if ((buffer[0] === 0xFF && buffer[1] === 0xFE) || (buffer[0] === 0xFE && buffer[1] === 0xFF)) {
      return 'utf16le'
    }
  }
  
  // 简单的中文编码检测
  let gbkCount = 0
  let utf8Count = 0
  
  for (let i = 0; i < Math.min(buffer.length, 1000); i++) {
    const byte = buffer[i]
    // GBK 编码范围检测
    if (byte >= 0xA1 && byte <= 0xFE) {
      gbkCount++
    }
    // UTF-8 编码检测
    if (byte >= 0x80) {
      utf8Count++
    }
  }
  
  // 如果有较多高位字节，可能是 GBK
  if (gbkCount > utf8Count && gbkCount > 10) {
    return 'gbk'
  }
  
  return 'utf8'
}

// IPC 处理文件选择
ipcMain.handle('select-txt-file', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openFile'],
    filters: [
      { name: 'Text Files', extensions: ['txt'] }
    ]
  })
  
  if (!result.canceled && result.filePaths.length > 0) {
    const filePath = result.filePaths[0]
    try {
      // 先读取文件的二进制数据
      const buffer = fs.readFileSync(filePath)
      const encoding = detectEncoding(buffer)
      
      let content
      if (encoding === 'gbk') {
        // 使用 iconv-lite 处理 GBK 编码
        const iconv = require('iconv-lite')
        content = iconv.decode(buffer, 'gbk')
      } else {
        content = buffer.toString(encoding)
      }
      
      return {
        success: true,
        content: content,
        fileName: path.basename(filePath),
        encoding: encoding,
        fileSize: buffer.length
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }
  
  return { success: false, error: '未选择文件' }
})